<template>
  <section class="content clearfix">
    <div class="col-sm-2" style="min-height:944px;background: #fff;">
      <div class="box box-info mytree ">
        <div class="box-header with-border">
          <h3 class="box-title current" @click="backList">分类列表</h3>
          <!--<button class="btn bg-green pull-right" @click="backList">返回列表</button>-->
        </div>
        <div class="form-horizontal">
          <div class="tree">
            <nav class='navbar'>
              <ul class='nav nav-stacked' v-for='(item,index) in allCategoryAnalysis' :key="index"> 
                <treeMenu :model="item" v-on:child-say='listenToMyBoy'></treeMenu>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>
    <div class="col-sm-10 mylist">
      <!--查询条件start-->
      <div class="box box-info myoption">
        <div class="box-header with-border">
          <h3 class="box-title">分类查询</h3>
        </div>
        <div class="form-horizontal seach-input">
          分类名称：
          <el-input class="myinput but-search"  @keyup.enter="searchSystematicName"
          placeholder="请输入您要查询的分类名称"  v-model="searchName"
          style="width:35%;height:40px;line-height:40px">
          </el-input>
          <el-button type="success" class="but-search"  @click="searchCategory">搜索</el-button>
          <el-button type="info"  @click="resetCategory">重置</el-button>
          <el-button type="primary"   data-toggle="modal" data-target="#modal-default"
            @click="addCategory" v-if="$_has('sys:category:add')">新增一级类目</el-button>
          <el-button type="primary"  @click="deleteAllCatorComfrim" v-if="$_has('sys:category:batchDelete')">批量删除</el-button>
        </div>
      </div>
      <!--查询条件end-->


      <!--数据展示start-->
      <div class="mytable">
          <el-table
          ref="classificatList"
          :data="classificatList"
          tooltip-effect="dark"
          style="width: 100%;font-size:14px; min-height: 690px;"
          :header-cell-style="{background:'#F5F7FA',height:'60px','line-height':'60px',color:'#606266','font-size':'14px'}"
          @row-click="clickRow" 
          @selection-change="handleSelectionChange">
          <el-table-column  align="center" 
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="分类名称"
          min-width="10%"  align="center" >
          </el-table-column>
          <el-table-column
            prop="categoryDesc"
            label="分类描述"
            min-width="20%"  align="center" >
          </el-table-column>
          <el-table-column
          fixed="right"
          label="操作"
          width="250px"  align="center">
          <template slot-scope="scope" >
            <div class="myicon-option">
               <i class="el-icon-myedit" @click="editorCategory(scope.row)" data-toggle="modal"
                       data-target="#modal-default" title="编辑" v-if="$_has('sys:category:edit')"></i>
              <i class="el-icon-addorigin"  data-toggle="modal" title="新增子级"  v-if="scope.row.categoryLevel<3"
                        data-target="#modal-default" @click="addNextCategory(scope.row)"></i>
              <i :class="scope.row.status == 1 ? 'el-icon-disable' : 'el-icon-able'" :title="scope.row.status ==1 ? '禁用' : '启用'"  v-if="$_has('sys:category:updateStatus')" @click="startAndEndComfrim(scope.row)"></i>
              <i class="el-icon-mydelete "  title="删除"  @click="deleteItemComfrim(scope.row)" v-if="$_has('sys:category:delete')"></i>
            </div>
           
          </template>
        </el-table-column>
        </el-table>
        <el-pagination class="page"
            background
            layout="total,prev, pager, next"
            :total="pages.total"
            :pager-count="6"
            :page-size="pages.display"
            @current-change ='pagechange'
            >
        </el-pagination>      
      </div>
      <!--数据展示end-->
    </div>
    <!--添加和编辑弹窗start-->
       <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
       <el-form ref="ClassificationFrom" :model="classificatList"  label-width="100px"  >   
          <el-form-item  v-if="superiorClassify"  label="父级名称:" >
              <label style="font-weight: inherit;">{{parentName}}</label>
             <el-input placeholder="请输入父级名称"    v-model="parentName" readonly="true"  style="display:none" ></el-input>
          </el-form-item>
            <el-form-item label="分类名称:" style="position:relative">
              <span style="position: absolute;left: -86px;top: 3px;color: red;">*</span>
              <el-input placeholder="请输入分类名称"   v-model="categoryName" style="width:90%"></el-input>
          </el-form-item>
          <el-form-item label="分类描述:">
              <el-input placeholder="请输入分类描述"   type="textarea"  v-model="categoryDesc" style="width:90%"></el-input>
          </el-form-item>
         <div style="text-align: center;">
            <el-button type="primary"   data-dismiss="modal" @click="submitCategory" v-if="categoryName">保存</el-button>
            <el-button type="primary"  @click="submitCategory" v-else>保存</el-button>
            <el-button data-dismiss="modal"  @click="dialogVisible = false">关闭</el-button>
         </div>
      </el-form>
    </el-dialog>
    <!--添加和编辑弹窗end-->

    <transition name="fade">
      <div v-if="errorShow" class="gritter-notice-wrapper " :class="{'success-notice-wrapper':errorClass}">
        <div id="gritter-item-4" class="gritter-item-wrapper gritter-error" style="" role="alert">
          <div class="gritter-item"><a class="gritter-close" tabindex="1" @click="closeError"><i
            class="fa fa-close"></i></a>
            <div class="gritter-without-image"><span class="gritter-title">{{errorTitle}}</span>
              <p>{{errorMsg}}</p></div>
          </div>
        </div>
      </div>
    </transition>
  </section>
</template>

<script>
  import ClassificationList from '@/js/product/ClassificationList'
  import instance from '@/api/index.js'
  import pagination from '@/components/common/pageComponent'
  import treeMenu from './treeMenu'

  export default {
    name: 'ClassificationList',
    data() {
      return {
        forEachIndex: 0,//递归下标
        productClassifyMap: new Map,//获取子叶商品分类
        productSelect: [],//解析Map数据
        classificationListL2: [],//存放二级菜单数据
        menus: [],
        allMenu:[],
        classificationList: [],//分类列表
        // classificatList:{
        //    parentName:'',
        //    categoryName:'',
        //    categoryDesc:''
        // },//获取一级分类
        classificatList: [],
        searchSystematic: {},//查询调节
        superiorClassify: false,
        addcategoryParam: {},//
        parentId: '',//获取父级名称
        allCategory: [],//获取所有分类
        allCategoryAnalysis: [],
        errorShow: false,//错误显示
        errorMsg: '',//错误信息
        errorTitle: '',//错误提示标题
        errorClass: false,//错误样式
        editorCa:false,
        list:[],
        pages:{
          current:1,
          display:10,
          total:0
        },
        classIficatParam:{},
        classIficatLTParam:{},
        judgeLevel:1,
        parentName:'',
        categoryName:'',
        categoryDesc:'',
        searchName:'',
        allProduct:'',//全选
        checkedProduct:[],
        searchParamsCator:{},
        menuListCheck:[],
        depositMenus:[],
        CategFlag:false,
        dialogVisible:false,//弹窗的显示隐藏
        multipleSelection:[],
        dialogTitle:"新增一级类目"
      }
    },
    components:{
      pagination,
      treeMenu
    },
    methods: {
       //获得当前选中数据
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //分页
      pagechange: function (currentPage) {
        if(!this.CategFlag){
          this.pages.current = currentPage;
          this.classIficatParam.page = currentPage;
          this.levelCategoryFn();
        }else {
          this.pages.current = currentPage;
          this.searchParamsCator.page = currentPage;
          this.pagesChangeListen();
        }
      },

      //获取一级分类
      levelCategoryFn:function(){
        let vm = this;
        vm.judgeLevel = 1;
        vm.classIficatParam.page = vm.pages.current;
        vm.classIficatParam.rows = 10;
        vm.pages.display = vm.classIficatParam.rows;
        vm.classIficatParam.categoryLevel = 1;
        instance({
          method:'post',
          url:'v1/goods/category/getList',
          params:vm.classIficatParam
        }).then(function (data) {
          vm.classificatList = data.data.data.list;
          vm.pages.total = data.data.data.total;
        })
      },

      //
      startAndEndComfrim:function(_obj){
        let vm = this;
        var status =""
        if(_obj.status == 1){
          status= "禁用"
        }else{
          status="启用"
        }
        vm.$confirm('此操作将此分类'+status+', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          vm.startAndEnd(_obj);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        })
      },

      //全选
      checkAllProduct:function(){
        let vm = this;
        if(!vm.allProduct){
          vm.checkedProduct = [];
          vm.show = false;
        }else {
          vm.checkedProduct = [];
          vm.show = true;
          vm.classificatList.forEach(function (item) {
            vm.checkedProduct.push(item)
          })
        }
      },
      //批量删除
      deleteAllCatorComfrim:function(){
  
        let vm = this;
        vm.$confirm('此操作将批量删除商品分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          vm.deleteAllCator();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },

      //批量删除
      deleteAllCator:function(){
        let vm = this;
        var ids =[]
        vm.multipleSelection.forEach(function(obj,ind,arr){
           ids.push(obj.categoryId)
        });
        if(vm.multipleSelection.length == 0){
    
          this.$message.error('请选择商品分类');
          return;
        }else {
          instance({
            method:'post',
            url:'v1/goods/category/batchDelete',
            data:{ids:ids}
          }).then(function (data) {
            if(data.data.success){
              if(!vm.CategFlag){
                vm.levelCategoryFn();
              }else {
                vm.pagesChangeListen();
              }
              vm.getAllCategory();
            }else {
            }
          })
        }
      },

      //启用禁用
      startAndEnd:function(_obj){
        let vm = this;
        let status = '';
        if(_obj.status == 0){
          status = 1;
        }else {
          status = 0;
        }
        instance({
          method:'post',
          url:'v1/goods/category/updateStatus',
          params:{
            categoryId:_obj.categoryId,
            status:status
          }
        }).then(function (data) {
          if(_obj.categoryLevel == 1){
            vm.levelCategoryFn();
          }else {
            vm.getLeaf();
          }
          if(data.data.success){
            vm.getAllCategory()
          }
        })
      },

      toggleChildren: function (item,id,name,pId) {
        item.expanded = !item.expanded;
        this.parentId = id;
        this.parentName = name;
        this.judgeLevel = 2;
        this.getLeaf();
      },

      //重置
      resetCategory:function(){
        this.searchName = '';
        this.searchCategory(1);
      },

      //搜索分类名称
      searchCategory:function(_type){
        let vm = this;
        if(!vm.searchName && _type != 1){
          this.$message.error('请填写分类名称');
          return;
        }
        if(vm.parentId){
          instance({
            method:'post',
            url:'v1/goods/category/getList',
            params:{
              page:vm.classIficatParam.page,
              rows:vm.classIficatParam.rows,
              categoryParentId:vm.parentId,
              categoryName:vm.searchName
            }
          }).then(function (data) {
            if(data.data.success){
              vm.classificatList = data.data.data.list;
            }
          })
        }else {
          this.$message.error('请选择一级分类');
          return;
        }
      },

      //获取点击分类列表
      listenToMyBoy:function(_obj){
        let vm = this;
        this.CategFlag = true;
        vm.searchParamsCator.rows = 10;
        vm.pages.current = 1;
        vm.searchParamsCator.page = vm.pages.current;
        vm.searchParamsCator.categoryParentId = _obj.categoryId;
        vm.parentId = _obj.categoryId;
          instance({
            method:'post',
            url:'v1/goods/category/getList',
            params:vm.searchParamsCator
          }).then(function (data) {
            vm.classificatList = data.data.data.list;
            vm.pages.total = data.data.data.total;
          })
      },

      pagesChangeListen:function(){
        let vm = this;
        this.CategFlag = true;
        vm.searchParamsCator.rows = 10;
        vm.searchParamsCator.page = vm.pages.current;
        vm.searchParamsCator.categoryParentId = vm.parentId;
        instance({
          method:'post',
          url:'v1/goods/category/getList',
          params:vm.searchParamsCator
        }).then(function (data) {
          vm.classificatList = data.data.data.list;
          vm.pages.total = data.data.data.total;
        })
      },

      getLeaf:function(){
        let vm = this;
        instance({
          method:'post',
          url:'v1/goods/category/getList',
          params:{
            page:vm.classIficatParam.page,
            rows:vm.classIficatParam.rows,
            categoryParentId:vm.parentId
          }
        }).then(function (data) {
          vm.classificatList = data.data.data.list;
          vm.pages.total = data.data.data.total;
          if(vm.pages.current != 1){
            vm.pages.current = 1;
          }
        })
      },


      //返回列表
      backList:function(){
        this.superiorClassify = false;
        for (let i = 0; i < this.allCategoryAnalysis.length; i++){
          this.allCategoryAnalysis[i].expanded = false;
        }
        this.searchName = '';
        this.parentId = null;
        this.levelCategoryFn();
      },

      //删除分类
      deleteItemComfrim:function(_obj){
        let vm = this;
        vm.$confirm('此操作将删除此分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          vm.deleteItem(_obj);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },

      //删除分类
      deleteItem: function (_obj) {
        let vm = this;
        instance({
          method: 'post',
          url: 'v1/goods/category/delete',
          params:{categoryId:_obj.categoryId}
        }).then(function (data) {
          if(_obj.categoryLevel == 1){
            vm.levelCategoryFn();
          }else {
            vm.getLeaf();
          }
          vm.getAllCategory();
        })
      },



      //获取所有商品分类树
      getAllCategory: function () {
        let vm = this;
        instance({
          method: 'post',
          url: '/v1/goods/category/getAll',
          params:{
            // isCategoryMaintain:1
          }
        }).then(function (data) {
          if (data.data.success) {
            let menus = data.data.data;
            vm.allMenu = menus;
            vm.menuListCheck = [];
            vm.getData(null,menus);
            vm.depositMenus = [];
            for (let i = 0; i < vm.menuListCheck.length; i++){
              if(vm.menuListCheck[i].categoryParentId == null){
                vm.depositMenus.push(vm.menuListCheck[i])
              }
            }
            vm.allCategoryAnalysis = vm.depositMenus;
          }
          //
          // vm.classificationListL2 = vm.allCategoryAnalysis
        })
      },

      getData: function (id, arry) {
        let vm = this;
        var childArry = this.familyTree(id, arry);
        if (childArry.length > 0) {
          for (var i = 0; i < childArry.length; i++) {
            let obj = {};
            obj = childArry[i];
            childArry[i].children = this.familyTree(childArry[i].categoryId, arry);
            childArry[i].show = false;
            vm.menuListCheck.push(obj);
            vm.getData(childArry[i].categoryId, arry);
          }
        }
      },
      //
      familyTree: function (id, arry) {
        var newArry = new Array();
        for (var i in arry) {
          if (arry[i].categoryParentId == id)
            newArry.push(arry[i]);
        }
        return newArry;
      },
      //商品分类-在某个分类下根据分类名称搜索
      systematicName: function (categoryId) {
        let vm = this;
        instance({
          method: 'post',
          url: '/v1/goods/category/getList',
          params: {
            "categoryParentId": categoryId
          }
        }).then(function (data) {
          vm.forEachIndex++;
          if (categoryId != null || categoryId != undefined) {
            vm.productClassifyMap.set(categoryId, data.data.data)
          }
          if (vm.classificationList[vm.forEachIndex]) {
            vm.systematicName(vm.classificationList[vm.forEachIndex].categoryId);
          } else {
            let arr = [], arr1 = [], i = 0;
            vm.productClassifyMap.forEach((value, key) => {
              arr.push(vm.productClassifyMap.get(key));
            });
            vm.productSelect = arr;
            for (let i = 0; i < vm.menus.length; i++) {
              vm.menus[i].children = vm.productSelect[i]
            }
            ;
            vm.forEachIndex = 0;
            return;
          }

        })
      },

      //获取下级分类
      getProductDetails: function (id) {
        let vm = this;
        vm.searchSystematic.categoryParentId = id;
        instance({
          method: 'post',
          url: '/v1/goods/category/getList',
          params: vm.searchSystematic
        }).then(function (data) {
          vm.classificationListL2 = data.data.data;
        })
      },

      //通过分类名称查询
      searchSystematicName() {
        let vm = this;
        // vm.searchSystematic.categoryName;
        // vm.searchSystematic.categoryParentId;
        instance({
          method: 'post',
          url: '/v1/goods/category/getList',
          params: vm.searchSystematic
        }).then(function (data) {
          vm.classificationListL2 = data.data.data;
        })
      },

      //添加一级类目或平台类目
      addCategory: function () {
      	this.dialogVisible = true;
        for (let key in this.addcategoryParam) {
          this.addcategoryParam[key] = "";
        }
        this.categoryDesc = '';
        this.categoryName ='';
        this.parentId = '';
        this.parentName = '';
        this.superiorClassify = false;
        this.dialogTitle="新增一级类目"
      
      },

      //编辑分类列表
      editorCategory:function(_obj){
        this.dialogVisible = true;
        this.dialogTitle="编辑一级类目"
        this.judgeLevel = _obj.categoryLevel;
        if(_obj.categoryLevel == 1){
          this.categoryDesc = _obj.categoryDesc;
          this.categoryName = _obj.categoryName;
          this.parentId = _obj.categoryId;
          this.superiorClassify = false;
          this.addcategoryParam.categoryId =  _obj.categoryId;
        }else {
          for (let i = 0; i < this.allMenu.length; i++){
            if(_obj.categoryParentId == this.allMenu[i].categoryId){
              this.parentName = this.allMenu[i].categoryName
            }
          }
          this.categoryName = _obj.categoryName;
          this.categoryDesc = _obj.categoryDesc;
          this.parentId = _obj.categoryParentId;
          this.addcategoryParam.categoryId =  _obj.categoryId;
          this.superiorClassify = true;
          this.dialogTitle="编辑子级类目"
        }
      },

      //添加下级分类列表
      addNextCategory: function (_obj) {
        this.dialogVisible = true;
        this.parentName = _obj.categoryName;
        this.dialogTitle="新增子级类目"
        this.superiorClassify = true;
        this.parentId = _obj.categoryId;
        this.categoryName = '';
        this.categoryDesc = '';
        this.categoryId = ""
      },

      //定时信息提示
      setTime: function () {
        let vm = this;
        setTimeout(function () {
          vm.errorShow = false;
        }, 2500)
      },

      //关闭信息提示
      closeError: function () {
        this.errorShow = false;
      },

      //保存类目
      submitCategory: function () {
        let vm = this;
        if(!vm.categoryName){
          this.$message.error('请填写分类名称');
          return;
        }
        vm.addcategoryParam.categoryParentId = vm.parentId
        if(vm.categoryDesc){
        	 vm.addcategoryParam.categoryDesc = vm.categoryDesc.trim();
        }else{
        	 vm.addcategoryParam.categoryDesc = vm.categoryDesc;
        }
        if(vm.categoryName){
        	vm.addcategoryParam.categoryName = vm.categoryName.trim();
        }else{
        	vm.addcategoryParam.categoryName = vm.categoryName;
        }
        instance({
          method: 'post',
          url: '/v1/goods/category/addOrEdit',
          data: vm.addcategoryParam
        }).then(function (data) {
          if(data.data.success){
            if(vm.judgeLevel == 1){
              vm.levelCategoryFn();
            }else {
              vm.pagesChangeListen();
            }
            vm.getAllCategory();
            vm.dialogVisible = false;
          }else{
            this.$message.error(data.data.msg);
             
          }
        })
      },
    },
    created() {
      // 获取商品分类
      // this.getClassificationList();
      this.levelCategoryFn();
      //获取所有商品分类树
      this.getAllCategory();
    },


  }
</script>

<style scoped lang="less">

.el-dialog__body{
	padding: 20px 20px;
}
.box.box-info{
  border-top:none;
  .box-header{
    &::before{
            content: "";
            display: inline;
            height: 30px;
            width: 2px;
            background-color: #67C23A;
            position: absolute;
            left: 0;
            top: 10px;
    }
  }
}
.mytree{
	box-shadow:none;
  .treeMenuSpan{
    line-height: 50px;
  }
  .glyphicon-chevron-right:before{
    content: "" !important;
    color: red;
    //background: url('../../../assets/img/myEdit.png')
  }
   .with-border{
     padding-left: 20px;
   }
}
.mylist{
  //条件查询
  .myoption{
      .with-border{
          padding-left: 20px;
      }
    .seach-input{
      color: #606266;
      font-size:14px;
      padding: 15px 0 15px 20px;
      .myinput{
        width: 370px;
        border-radius: 4px;
        
      }
      button{
        padding: 12px 21px;
        margin: 0 9px;
        border-radius: 4px;
            &.but-search{
            margin-left: 20px;
          }
      }
    }
  }
  .mytable{
    font-size: 14px;
    margin-top: 30px;
     background: #fff;
     padding:20px;
     clear: both;
     overflow: hidden;
     .page{
      margin: 20px 0 5px;
       float: right;
    }
    .cell{
       display: flex;
      justify-content: center;
      align-items: center;
      .myicon-option{
        font-size: 18px;
        color: #409EFF;
        margin: 6px;
        cursor:pointer;
      
        i{
          display: inline-block;
          width: 18px;
          height: 18px;
          margin:  0 12px;
          &.el-icon-myedit{
            background:url('../../../assets/img/myEdit.png') no-repeat; 
            background-size: 100%;
          }
            &.el-icon-addorigin{
              background:url('../../../assets/img/myOriginAdd.png') no-repeat; 
              background-size: 100%;
               width: 29px;
            }
             &.el-icon-disable{
              background:url('../../../assets/img/myDisable.png') no-repeat; 
              background-size: 100%;
            }
             &.el-icon-able{
              background:url('../../../assets/img/myAble.png') no-repeat; 
              background-size: 100%;
            }
             &.el-icon-mydelete{
              background:url('../../../assets/img/myDelete.png') no-repeat; 
              background-size: 100%;
            }
        }
      } 
    }     
  }
}
  
</style>
